package com.budwk.app.sqfw.services.impl;

import com.alibaba.fastjson.JSONObject;
import com.budwk.app.common.config.AppException;
import com.budwk.app.sqfw.component.OppoComponent;
import com.budwk.app.sqfw.services.OppoInterfaceService;
import com.budwk.starter.common.constant.RedisConstant;
import com.budwk.starter.common.result.Result;
import com.budwk.starter.common.result.ResultCode;
import com.oppo.push.server.Notification;
import com.oppo.push.server.Sender;
import com.oppo.push.server.Target;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.nutz.integration.jedis.RedisService;
import org.nutz.ioc.impl.PropertiesProxy;
import org.nutz.ioc.loader.annotation.Inject;
import org.nutz.ioc.loader.annotation.IocBean;

import java.io.IOException;
import java.util.Optional;

/**
 * @title: oppo接口服务
 */

@IocBean
@Slf4j
public class OppoInterfaceServiceImpl implements OppoInterfaceService {

    @Inject
    private OppoComponent oppoComponent;

    @Inject
    private PropertiesProxy propertiesProxy;

    @Inject
    private RedisService redisService;

    @Override
    public void pushOppoMessage(String msgContent, String action, String token, String sqfwId) {
        try {
            // 1 获取发送sender
            Sender sender = oppoComponent.pushSender();
            // 2 创建通知栏消息体
            Notification notification = oppoComponent.getNotification(msgContent, action, sqfwId);
            // 3 创建推送目标对象，传入注册ID
            Target target = Target.build(token);
            // 调用单推接口，推送消息，获得调用结果
            com.oppo.push.server.Result result = sender.unicastNotification(notification, target);
            log.info("oppo push message res: {}", JSONObject.toJSONString(result));
            // 4 解析结果
            if (result == null) {
                throw new AppException(ResultCode.SERVER_ERROR.getMsg());
            }
            if (result.getStatusCode() != 200) {
                throw new AppException(result.getReason());
            }
        } catch (Exception e) {
            log.error("oppo push message error: ", e);
            throw new AppException(e.getMessage());
        }
    }

    @Override
    public Result<?> getOppoApplyLatestVersion() throws IOException {
        // 1 从redis中获取
        String redisDataKey = RedisConstant.WKCACHE + "oppo:getOnlineVersion:url:data";
        String versionData = redisService.get(redisDataKey);
        if (StringUtils.isNotEmpty(versionData)) {
            return Result.success(JSONObject.parseObject(versionData));
        }
        // 2 远程查询接口获取
        Optional<String> optional = oppoComponent.getAccessToken();
        Result result = oppoComponent.queryOppoApplyLatestVersion(optional.get());
        if (result.isSuccess()) {
            // 存入redis缓存
            redisService.setex(redisDataKey, 1000, JSONObject.toJSONString(result.getData()));
        }
        return result;
    }
}
